package codeMaker.impl;

import codeMaker.TablesQuery;
import constant.ChildWindowConstant;
import constant.CodeConstant;
import constant.CompareComboBox;
import constant.FiledComment;
import constant.Filed_cn;
import constant.Filed_eng;
import constant.OrderComboBox;
import constant.RelationJcombox;
import constant.ServiceTypeComboBox;
import constant.Table1;
import constant.Table1Fileds;
import constant.Table2;
import constant.Table2Fileds;
import entity.DataSourceModel;
import entity.Parameters;
import entity.TableConditionModel;
import entity.TableFiledModel;
import entity.TableRelationModel;
import entity.TablesQueryModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName TablesQueryImpl
 * @Author zrx
 * @Date 2021/11/23 22:29
 */
public class TablesQueryImpl extends TablesQuery {

	private static volatile TablesQueryImpl tablesQueryImpl;

	public static TablesQueryImpl getInstance() {
		if (null == tablesQueryImpl) {
			synchronized (TablesQueryImpl.class) {
				if (null == tablesQueryImpl) {
					tablesQueryImpl = new TablesQueryImpl();
				}
			}
		}
		return tablesQueryImpl;
	}

	private TablesQueryImpl() {
		super();
	}

	/**
	 * 方法下拉框
	 *
	 * @param tableConfigExit
	 * @param methodListCombox
	 * @param conditionPanel
	 * @param querysPanel
	 * @param tablesPanel
	 * @param tablesArr
	 * @param querysArr
	 * @param conditionsArr
	 */
	public void setMethodComboxListener(JComboBox<String> tableConfigExit, JComboBox<String> methodListCombox, JPanel conditionPanel, JPanel querysPanel, JPanel tablesPanel, String[] tablesArr, String[] querysArr, String[] conditionsArr) {
		methodListCombox.addItemListener(e -> {

			if (e.getStateChange() != ItemEvent.SELECTED) {
				return;
			}

			// 选取的当前方法名
			String currentMethod = methodListCombox.getSelectedItem().toString();

			if ("--请选择--".equals(currentMethod)) {

				tablesPanel.removeAll();
				querysPanel.removeAll();
				conditionPanel.removeAll();

				methodNameField.setText("");
				methodName_cnField.setText("");

				frame.validate();
				frame.repaint();

				return;

			}

			// 选取的模块名
			String currentModel = tableConfigExit.getSelectedItem().toString();

			// 选择的当前方法名
			TablesQueryModel tablesQueryModel = ChildWindowConstant.tablesQueryMap.get(currentModel)
					.get(currentMethod);
			// 动态设置方法名称和中文名称
			methodNameField.setText(currentMethod);
			methodName_cnField.setText(tablesQueryModel.getMethodName_cn());
			entityNameField.setText(tablesQueryModel.getEntityName());
			entityName_cnField.setText(tablesQueryModel.getEntityName_cn());

			List<TableRelationModel> tableRelations = tablesQueryModel.getTableRelationModelLists();

			List<TableFiledModel> tableFileds = tablesQueryModel.getTableFiledModels();

			List<TableConditionModel> tableConditions = tablesQueryModel.getTableConditionModels();

			// 移除三个panel所有的组件
			tablesPanel.removeAll();
			querysPanel.removeAll();
			conditionPanel.removeAll();

			// 加入表头和内容
			for (String tableStr : tablesArr) {
				JLabel label1 = new JLabel(tableStr);
				tablesPanel.add(label1);
			}
			for (TableRelationModel tableRelation : tableRelations) {

				tablesPanel.add(tableRelation.getComboBox());
				tablesPanel.add(tableRelation.getTable1());
				tablesPanel.add(tableRelation.getTable2());
				tablesPanel.add(tableRelation.getTable1Fileds());
				tablesPanel.add(tableRelation.getTable2Fileds());

			}

			for (String queryStr : querysArr) {
				JLabel label1 = new JLabel(queryStr);
				querysPanel.add(label1);
			}
			for (TableFiledModel tableFiled : tableFileds) {

				querysPanel.add(tableFiled.getComboBox());
				querysPanel.add(tableFiled.getFiled_eng());
				querysPanel.add(tableFiled.getFiled_cn());
				querysPanel.add(tableFiled.getServiceTypeComboBox());
				querysPanel.add(tableFiled.getTextFiled());
				querysPanel.add(tableFiled.getOrderComboBox());

			}

			for (String conditionStr : conditionsArr) {
				JLabel label1 = new JLabel(conditionStr);
				conditionPanel.add(label1);
			}
			for (TableConditionModel tableCondition : tableConditions) {

				conditionPanel.add(tableCondition.getRelationJcombox());
				conditionPanel.add(tableCondition.getComboBox());
				conditionPanel.add(tableCondition.getFiled_eng_textFiled());
				conditionPanel.add(tableCondition.getFiled_cn_textFiled());
				conditionPanel.add(tableCondition.getServiceTypeComboBox());
				conditionPanel.add(tableCondition.getFiledComment());
				conditionPanel.add(tableCondition.getCompareComboBox());
				conditionPanel.add(tableCondition.getTextFiled());

			}

			frame.validate();
			frame.repaint();

		});
	}

	/**
	 * 模块下拉框
	 *
	 * @param tableConfigExit
	 * @param methodListCombox
	 * @param conditionPanel
	 * @param querysPanel
	 * @param tablesPanel
	 */
	public void setTableConfigExitListener(JComboBox<String> tableConfigExit, JComboBox<String> methodListCombox, JPanel conditionPanel, JPanel querysPanel, JPanel tablesPanel) {
		tableConfigExit.addItemListener(e -> {

			if (e.getStateChange() != ItemEvent.SELECTED) {
				return;
			}

			// 选取的当前模块
			String currentModel = tableConfigExit.getSelectedItem().toString();

			if ("--请选择--".equals(currentModel)) {

				tablesPanel.removeAll();
				querysPanel.removeAll();
				conditionPanel.removeAll();

				currentModelName.setText("");
				currentModelName_cn.setText("");
				methodNameField.setText("");
				methodName_cnField.setText("");
				entityNameField.setText("");
				entityName_cnField.setText("");
				methodListCombox.setModel(new DefaultComboBoxModel<>(new String[]{"--请选择--"}));

				frame.validate();
				frame.repaint();

				return;

			}

			currentModelName.setText(currentModel);

			String currentCnModelName = ChildWindowConstant.tablesQueryEndAndCnMap.get(currentModel);

			currentModelName_cn.setText(currentCnModelName);

			// 获取对应的方法列表
			String[] methods = ChildWindowConstant.tablesQueryMap.get(currentModel).keySet()
					.toArray(new String[]{});

			// 根据当前模块设置方法
			methodListCombox.setModel(new DefaultComboBoxModel<>(new String[]{"--请选择--"}));

			for (String methodName : methods) {
				methodListCombox.addItem(methodName);
			}

			frame.validate();
			frame.repaint();

		});
	}

	/**
	 * 关联确定
	 *
	 * @param addQuery
	 * @param addCondition
	 * @param confirmRelTable
	 * @param conditionPanel
	 * @param querysPanel
	 * @param tablesPanel
	 * @param tableRelationModelLists
	 * @param tableMap
	 */
	public void setConfirmRelTableListener(JButton addQuery, JButton addCondition, JButton confirmRelTable, JPanel conditionPanel, JPanel querysPanel, JPanel tablesPanel, List<TableRelationModel> tableRelationModelLists, Map<String, String> tableMap) {
		confirmRelTable.addActionListener(e -> {

			if (!checkRelTable(tablesPanel, tableRelationModelLists, tableMap)) {
				return;
			}

			addQuery.setEnabled(true);
			addCondition.setEnabled(true);

			Component[] queryComponents = querysPanel.getComponents();

			for (int i = 6; i < queryComponents.length; i++) {

				if ("JComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					JComboBox<String> comboBox = (JComboBox<String>) queryComponents[i];

					Set<String> tables = tableMap.keySet();

					comboBox.removeAllItems();

					for (String table : tables) {
						comboBox.addItem(table);
					}

				}
			}

			Component[] conditionComponents = conditionPanel.getComponents();

			for (int i = 8; i < conditionComponents.length; i++) {

				if ("JComboBox".equals(conditionComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					JComboBox<String> comboBox = (JComboBox<String>) conditionComponents[i];

					Set<String> tables = tableMap.keySet();

					comboBox.removeAllItems();

					for (String table : tables) {
						comboBox.addItem(table);
					}

				}
			}

			frame.validate();
			frame.repaint();

		});
	}

	/**
	 * 最终确定
	 *
	 * @param parameters
	 * @param addQuery
	 * @param confirm
	 * @param addCondition
	 * @param tableConfigExit
	 * @param methodListCombox
	 * @param conditionPanel
	 * @param querysPanel
	 * @param tablesPanel
	 * @param tableRelationModelLists
	 * @param tableMap
	 */
	public void setConfirmListener(Parameters parameters, JButton addQuery, JButton confirm, JButton addCondition, JComboBox<String> tableConfigExit, JComboBox<String> methodListCombox, JPanel conditionPanel, JPanel querysPanel, JPanel tablesPanel, List<TableRelationModel> tableRelationModelLists, Map<String, String> tableMap) {
		confirm.addActionListener(e -> {

			String modelName = currentModelName.getText();
			//判断模块名是否与其他数据源有重复
			for (Map.Entry<String, DataSourceModel> entry : ChildWindowConstant.dataSourceModelMap.entrySet()) {
				String dataSource = entry.getKey();
				DataSourceModel dataSourceModel = entry.getValue();
				//如果不是自己
				if (!dataSource.equals(parameters.getDataSourceName())) {
					//如果其他数据源也包含该模块名
					if (dataSourceModel.getTablesQueryMap().containsKey(modelName)) {
						JOptionPane.showMessageDialog(frame, "模块名与数据源 " + dataSource + " 重复了，换个模块名吧！", "错误", JOptionPane.ERROR_MESSAGE);
						return;
					}
				}
			}
			currentModelName.setText(modelName);

			String modelNameCn = currentModelName_cn.getText();
			currentModelName_cn.setText(modelNameCn);

			// 当前模块方法名
			String methodName = methodNameField.getText();
			methodNameField.setText(methodName);

			// 当前模块的方法中文名称
			String methodName_cn = methodName_cnField.getText();
			methodName_cnField.setText(methodName_cn);

			// 当前的实体名称
			String entityName = entityNameField.getText();
			entityNameField.setText(entityName);

			// 当前实体的中文名称
			String entityName_cn = entityName_cnField.getText();
			entityName_cnField.setText(entityName_cn);

			if ("".equals(modelName) || "".equals(methodName) || "".equals(entityName)) {
				JOptionPane.showMessageDialog(frame, "模块名，方法名，实体名不可以为空！请填写！", "错误", JOptionPane.ERROR_MESSAGE);
				return;
			}

			// 为中文模块名赋值
			modelNameCn = "".equals(modelNameCn) ? modelName : modelNameCn;

			// 为中文方法名赋值
			methodName_cn = "".equals(methodName_cn) ? methodName : methodName_cn;

			// 为实体中文名称赋值
			entityName_cn = "".equals(entityName_cn) ? entityName : entityName_cn;

			// 检查关联表部分的填写情况
			if (!checkRelTable(tablesPanel, tableRelationModelLists, tableMap)) {
				return;
			}

			// 开始拼sql。。。
			StringBuilder selectTableSql = new StringBuilder();

			String unsualFix = "";

			if ("mysql".equals(parameters.getDataBaseTypeVal())) {
				unsualFix = "`";
			}

			for (int i = 0; i < tableRelationModelLists.size(); i++) {

				TableRelationModel tableRelationModel = tableRelationModelLists.get(i);

				// 如果是第一个
				String anotherTableName = tableRelationModel.getAnotherTableName();

				String table2Text = tableRelationModel.getTable2_text();

				if (i == 0) {

					selectTableSql.append(" ").append(tableRelationModel.getRelation()).append(" ").append(unsualFix).append(tableRelationModel.getTable1_text()).append(unsualFix).append(" ").append(anotherTableName).append(" ");
					continue;
				}

				selectTableSql.append(" ").append(tableRelationModel.getRelation()).append(" ").append(unsualFix).append(tableRelationModel.getTable1_text()).append(unsualFix).append(" ").append(anotherTableName).append(" ON ");

				String table1Fileds = tableRelationModel.getTable1Fileds_text();
				String table2Fileds = tableRelationModel.getTable2Fileds_text();

				String[] table1FiledsArr = table1Fileds.split("&");
				String[] table2FiledsArr = table2Fileds.split("&");

				if (table1FiledsArr.length != table2FiledsArr.length) {
					JOptionPane.showMessageDialog(frame, "关联表配置中第  " + (i + 1) + " 行表1和表2的关联字段的个数不相等，请检查后重新配置！",
							"错误", JOptionPane.ERROR_MESSAGE);
					return;
				}

				for (int j = 0; j < table1FiledsArr.length; j++) {

					if (j == table1FiledsArr.length - 1) {
						selectTableSql.append(anotherTableName).append(".").append(table1FiledsArr[j]).append(" = ").append(tableMap.get(table2Text)).append(".").append(table2FiledsArr[j]);
						break;
					}

					selectTableSql.append(anotherTableName).append(".").append(table1FiledsArr[j]).append(" = ").append(tableMap.get(table2Text)).append(".").append(table2FiledsArr[j]).append(" and ");

				}

			}

			// System.out.println(selectTableSql);

			// 查询部分
			Component[] queryComponents = querysPanel.getComponents();
			List<TableFiledModel> tableFiledModels = new ArrayList<>();
			// 查询panel的信息
			for (int i = 6; i < queryComponents.length; i++) {

				if ("JComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					JComboBox<String> comboBox = (JComboBox<String>) queryComponents[i];

					TableFiledModel filedModel = new TableFiledModel();

					filedModel.setComboBox(comboBox);

					filedModel.setTableName((String) comboBox.getSelectedItem());

					filedModel.setAnotherTableName(tableMap.get(String.valueOf(comboBox.getSelectedItem())));

					tableFiledModels.add(filedModel);
				} else if ("Filed_eng".equals(queryComponents[i].getClass().getSimpleName())) {
					Filed_eng filedEng = (Filed_eng) queryComponents[i];

					String engFiled = filedEng.getText();
					filedEng.setText(filedEng.getText());

					if ("".equals(engFiled)) {
						JOptionPane.showMessageDialog(frame, "添加查询字段中的字段列不能为空！请填写！！", "错误",
								JOptionPane.ERROR_MESSAGE);
						return;
					}

					TableFiledModel tableFiledModel = tableFiledModels.get(tableFiledModels.size() - 1);

					tableFiledModel.setFiled_eng(filedEng);
					tableFiledModel.setFiledText_eng(engFiled);
					tableFiledModel.setAnotherFiledName(tableFiledModel.getAnotherTableName() + "_" + engFiled);
				} else if ("Filed_cn".equals(queryComponents[i].getClass().getSimpleName())) {

					Filed_cn filedCn = (Filed_cn) queryComponents[i];

					String cnFiled = filedCn.getText();
					filedCn.setText(cnFiled);

					if ("".equals(cnFiled)) {
						JOptionPane.showMessageDialog(frame, "添加查询字段中的中文名称列不能为空！请填写！！", "错误",
								JOptionPane.ERROR_MESSAGE);
						return;
					}

					tableFiledModels.get(tableFiledModels.size() - 1).setFiled_cn(filedCn);
					tableFiledModels.get(tableFiledModels.size() - 1).setFiledText_cn(cnFiled);
				} else if ("ServiceTypeComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) queryComponents[i];

					String filedType = (String) serviceTypeComboBox.getSelectedItem();

					tableFiledModels.get(tableFiledModels.size() - 1).setServiceTypeComboBox(serviceTypeComboBox);
					tableFiledModels.get(tableFiledModels.size() - 1).setFiledType(filedType);

				} else if ("FiledComment".equals(queryComponents[i].getClass().getSimpleName())) {

					FiledComment filedComment = (FiledComment) queryComponents[i];

					String comment = filedComment.getText();
					filedComment.setText(comment);

					String[] serviceArr = comment.split("#");

					TableFiledModel tableFiledModel = tableFiledModels.get(tableFiledModels.size() - 1);

					tableFiledModel.setTextFiled(filedComment);
					tableFiledModel.setFiledCommentStr(comment);

					String filedType = tableFiledModel.getFiledType();

					Map<String, Object> map = new HashMap<>();
					if ("布尔".equals(filedType)) {
						try {
							map.put("是", serviceArr[0]);
							map.put("否", serviceArr[1]);
							tableFiledModel.setFiledComment(map);
						} catch (Exception e1) {
							JOptionPane.showMessageDialog(frame, "布尔值的类型描述填写有误，请检查重写！", "错误",
									JOptionPane.ERROR_MESSAGE);
							return;
						}
					}

					if ("状态码".equals(filedType)) {
						try {
							for (String serviece : serviceArr) {
								String[] arr = serviece.split("&");
								map.put(arr[0], arr[1]);
							}
							tableFiledModel.setFiledComment(map);
						} catch (Exception e1) {
							JOptionPane.showMessageDialog(frame, "状态码的类型描述填写有误，请检查重写！", "错误",
									JOptionPane.ERROR_MESSAGE);
							return;
						}
					}
				} else if ("OrderComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					OrderComboBox<String> orderComboBox = (OrderComboBox<String>) queryComponents[i];

					String canSort = (String) orderComboBox.getSelectedItem();

					tableFiledModels.get(tableFiledModels.size() - 1).setOrderComboBox(orderComboBox);

					tableFiledModels.get(tableFiledModels.size() - 1).setCanSort(canSort);

				}

			}

			if (tableFiledModels.size() == 0) {
				JOptionPane.showMessageDialog(frame, "请配置查询字段信息！", "错误", JOptionPane.ERROR_MESSAGE);
				return;
			}

			// 条件部分
			Component[] conditionComponents = conditionPanel.getComponents();

			List<TableConditionModel> tableConditionModels = new ArrayList<>();
			// 条件panel的信息
			for (int i = 6; i < conditionComponents.length; i++) {

				if ("RelationJcombox".equals(conditionComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					RelationJcombox<String> comboBox = (RelationJcombox<String>) conditionComponents[i];

					TableConditionModel conditionModel = new TableConditionModel();

					conditionModel.setRelationJcombox(comboBox);
					conditionModel.setRelation((String) comboBox.getSelectedItem());

					tableConditionModels.add(conditionModel);

				} else if ("JComboBox".equals(conditionComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					JComboBox<String> comboBox = (JComboBox<String>) conditionComponents[i];

					tableConditionModels.get(tableConditionModels.size() - 1).setComboBox(comboBox);
					comboBox.setSelectedItem(comboBox.getSelectedItem());
					// 设置表名
					tableConditionModels.get(tableConditionModels.size() - 1)
							.setTableName((String) comboBox.getSelectedItem());

					// 设置表别名
					tableConditionModels.get(tableConditionModels.size() - 1)
							.setAnotherTableName(tableMap.get((String) comboBox.getSelectedItem()));
				} else if ("Filed_eng".equals(conditionComponents[i].getClass().getSimpleName())) {
					Filed_eng filedEng = (Filed_eng) conditionComponents[i];

					String engFiled = filedEng.getText();
					filedEng.setText(engFiled);

					if ("".equals(engFiled)) {
						JOptionPane.showMessageDialog(frame, "添加条件字段中的字段列不能为空！请填写！！", "错误",
								JOptionPane.ERROR_MESSAGE);
						return;
					}

					tableConditionModels.get(tableConditionModels.size() - 1).setFiled_eng_textFiled(filedEng);
					tableConditionModels.get(tableConditionModels.size() - 1).setFiled_eng(engFiled);
				} else if ("Filed_cn".equals(conditionComponents[i].getClass().getSimpleName())) {

					Filed_cn filedCn = (Filed_cn) conditionComponents[i];

					String cnFiled = filedCn.getText();
					filedCn.setText(cnFiled);

					if ("".equals(cnFiled)) {
						JOptionPane.showMessageDialog(frame, "添加条件字段中的中文名称列不能为空！请填写！！", "错误",
								JOptionPane.ERROR_MESSAGE);
						return;
					}

					tableConditionModels.get(tableConditionModels.size() - 1).setFiled_cn_textFiled(filedCn);
					tableConditionModels.get(tableConditionModels.size() - 1).setFiled_cn(cnFiled);
				} else if ("ServiceTypeComboBox".equals(conditionComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) conditionComponents[i];

					String filedType = (String) serviceTypeComboBox.getSelectedItem();

					tableConditionModels.get(tableConditionModels.size() - 1)
							.setServiceTypeComboBox(serviceTypeComboBox);
					tableConditionModels.get(tableConditionModels.size() - 1).setServiceType(filedType);

				} else if ("FiledComment".equals(conditionComponents[i].getClass().getSimpleName())) {

					FiledComment filedComment = (FiledComment) conditionComponents[i];

					String comment = filedComment.getText();
					filedComment.setText(comment);

					String[] serviceArr = comment.split("#");

					TableConditionModel tableConditionModel = tableConditionModels
							.get(tableConditionModels.size() - 1);

					tableConditionModel.setFiledComment(filedComment);

					String filedType = tableConditionModel.getServiceType();

					Map<String, Object> map = new HashMap<>();
					if ("布尔".equals(filedType)) {
						try {
							map.put("是", serviceArr[0]);
							map.put("否", serviceArr[1]);
							tableConditionModel.setServiceText(map);
						} catch (Exception e1) {
							JOptionPane.showMessageDialog(frame, "布尔值的类型描述填写有误，请检查重写！", "错误",
									JOptionPane.ERROR_MESSAGE);
							return;
						}
					}

					if ("状态码".equals(filedType)) {
						try {
							for (String serviece : serviceArr) {
								String[] arr = serviece.split("&");
								map.put(arr[0], arr[1]);
							}
							tableConditionModel.setServiceText(map);
						} catch (Exception e1) {
							JOptionPane.showMessageDialog(frame, "状态码的类型描述填写有误，请检查重写！", "错误",
									JOptionPane.ERROR_MESSAGE);
							return;
						}
					}
				} else if ("CompareComboBox".equals(conditionComponents[i].getClass().getSimpleName())) {

					@SuppressWarnings("unchecked")
					CompareComboBox<String> compareComboBox = (CompareComboBox<String>) conditionComponents[i];

					String compareText = (String) compareComboBox.getSelectedItem();

					tableConditionModels.get(tableConditionModels.size() - 1).setCompareComboBox(compareComboBox);
					tableConditionModels.get(tableConditionModels.size() - 1).setCompareText(compareText);

				} else if ("JTextField".equals(conditionComponents[i].getClass().getSimpleName())) {

					JTextField textField = (JTextField) conditionComponents[i];

					String unchangeValue = textField.getText();
					textField.setText(unchangeValue);

					tableConditionModels.get(tableConditionModels.size() - 1).setTextFiled(textField);
					tableConditionModels.get(tableConditionModels.size() - 1).setUnchangeValue(unchangeValue);

				}

			}

			if (tableConditionModels.size() == 0) {
				JOptionPane.showMessageDialog(frame, "请配置条件字段信息！", "错误", JOptionPane.ERROR_MESSAGE);
				return;
			}

			// 多表配置对象
			TablesQueryModel tablesQueryModel = new TablesQueryModel();

			// 储存多表查询的信息配置
			tablesQueryModel.setFormSql(selectTableSql.toString());
			List<TableRelationModel> realTableRelationModelLists = new ArrayList<>(tableRelationModelLists);
			tablesQueryModel.setTableRelationModelLists(realTableRelationModelLists);
			tablesQueryModel.setTableFiledModels(tableFiledModels);
			tablesQueryModel.setTableConditionModels(tableConditionModels);

			// 如果当前模块存在当前配置的方法名称
			Map<String, TablesQueryModel> methodMap = ChildWindowConstant.tablesQueryMap.get(modelName);

			if (ChildWindowConstant.tablesQueryMap.containsKey(modelName)) {

				// 如果已经配置了同名的方法，询问时候覆盖
				if (methodMap.containsKey(methodName)) {
					int getCodeConfirmDialog = JOptionPane.showConfirmDialog(frame,
							"当前模块‘" + modelName + "’下的方法‘" + methodName + "’已存在，确认覆盖？", "提示",
							JOptionPane.YES_NO_OPTION);

					if (getCodeConfirmDialog != 0) {
						return;
					}
				}
			}

			// 如果当前模块下没有配置任何method

			if (methodMap == null) {

				methodMap = new HashMap<>();
			}

			tablesQueryModel.setMethodName_cn(methodName_cn);
			tablesQueryModel.setEntityName(entityName);
			tablesQueryModel.setEntityName_cn(entityName_cn);

			// 存储方法对应的sql
			methodMap.put(methodName, tablesQueryModel);

			// 添加到当前模块中
			ChildWindowConstant.tablesQueryMap.put(modelName, methodMap);

			// 存储当前模块的英文名和中文名
			ChildWindowConstant.tablesQueryEndAndCnMap.put(modelName, modelNameCn);

			JOptionPane.showMessageDialog(frame, "当前模块配置成功！", "提示", JOptionPane.INFORMATION_MESSAGE);

			String[] modelArr1 = ChildWindowConstant.tablesQueryMap.keySet().toArray(new String[]{});

			tableConfigExit.setModel(new DefaultComboBoxModel<>(new String[]{"--请选择--"}));

			methodListCombox.setModel(new DefaultComboBoxModel<>(new String[]{"--请选择--"}));

			for (String model : modelArr1) {
				tableConfigExit.addItem(model);
			}

			currentModelName.setText("");
			currentModelName_cn.setText("");
			methodNameField.setText("");
			methodName_cnField.setText("");
			entityNameField.setText("");
			entityName_cnField.setText("");

			tablesPanel.removeAll();
			querysPanel.removeAll();
			conditionPanel.removeAll();

			addQuery.setEnabled(false);
			addCondition.setEnabled(false);

			frame.validate();
			frame.repaint();

		});
	}

	public void setRestartListener(JButton restart, JPanel conditionPanel, JPanel querysPanel, JPanel tablesPanel) {
		restart.addActionListener(e -> {
			clearPanel(conditionPanel, querysPanel, tablesPanel);
		});
	}

	public void setDeleteConditionListener(JButton deleteCondition, JPanel conditionPanel) {
		deleteCondition.addActionListener(e -> {

			// 获取容器个数
			int componentCount = conditionPanel.getComponentCount();

			if (componentCount == 0) {
				return;
			}
			// 一行有8个
			// 如果是16，全部移除
			if (componentCount == 16) {
				conditionPanel.removeAll();
				// 否则，移除最后6个
			} else {
				conditionPanel.remove(componentCount - 1);
				conditionPanel.remove(componentCount - 2);
				conditionPanel.remove(componentCount - 3);
				conditionPanel.remove(componentCount - 4);
				conditionPanel.remove(componentCount - 5);
				conditionPanel.remove(componentCount - 6);
				conditionPanel.remove(componentCount - 7);
				conditionPanel.remove(componentCount - 8);
			}

			frame.validate();
			frame.repaint();

		});
	}

	public void setAddConditionListener(JButton addCondition, JPanel conditionPanel, String[] conditionsArr, Map<String, String> tableMap) {
		addCondition.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if (!canAddCondition(conditionPanel)) {
					return;
				}

				if (conditionPanel.getComponentCount() == 0) {
					for (String conditionArr : conditionsArr) {
						JLabel label = new JLabel(conditionArr);
						conditionPanel.add(label);
					}
					addConditionMethod(conditionPanel);
					conditionPanel.getComponent(8).setVisible(false);
				} else {
					addConditionMethod(conditionPanel);
				}

				frame.validate();
				frame.repaint();
			}

			private boolean canAddCondition(JPanel conditionPanel) {

				if (conditionPanel.getComponentCount() >= 16) {

					Component[] components = conditionPanel.getComponents();

					for (int i = 8; i < components.length; i++) {

						if ("Filed_eng".equals(components[i].getClass().getSimpleName())) {

							Filed_eng filed_eng = (Filed_eng) components[i];
							filed_eng.setText(filed_eng.getText());

							if ("".equals(filed_eng.getText())) {
								JOptionPane.showMessageDialog(frame, "请先把当前内容填写完毕再增加条件字段信息！", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						} else if ("Filed_cn".equals(components[i].getClass().getSimpleName())) {

							Filed_cn filed_cn = (Filed_cn) components[i];
							filed_cn.setText(filed_cn.getText());

							if ("".equals(filed_cn.getText())) {
								JOptionPane.showMessageDialog(frame, "请先把当前内容填写完毕再增加条件字段信息！", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						} else if ("ServiceTypeComboBox".equals(components[i].getClass().getSimpleName())) {

							@SuppressWarnings("unchecked")
							ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) components[i];

							if ("布尔".equals(serviceTypeComboBox.getSelectedItem())
									|| "状态码".equals(serviceTypeComboBox.getSelectedItem())) {

								FiledComment filedComment = (FiledComment) components[i + 1];

								if ("".equals(filedComment.getText())) {

									JOptionPane.showMessageDialog(frame, "布尔或状态码的类型描述不能为空！！详细请见配置说明！", "提示",
											JOptionPane.INFORMATION_MESSAGE);
									return false;
								}

							}
						}

					}
				}

				return true;
			}

			private void addConditionMethod(JPanel conditionsPanel) {

				// 关联关系
				JComboBox<String> relationComBox = new RelationJcombox<>();

				relationComBox.setModel(new DefaultComboBoxModel<>(new String[]{"and", "or"}));

				// 表名
				Set<String> tables = tableMap.keySet();
				String[] tableArr = tables.toArray(new String[]{});
				JComboBox<String> tableName = new JComboBox<>(tableArr);

				// 字段
				JTextField tableFiled = new Filed_eng();

				// 中文名称
				JTextField tableFiled_cn = new Filed_cn();

				// 字段类型
				JComboBox<String> filedType = new ServiceTypeComboBox<>();

				String[] typeList = new String[]{"字符串", "数字", "布尔", "状态码", "日期", "文字域"};

				filedType.setModel(new DefaultComboBoxModel<String>(typeList));

				FiledComment filedComment = new FiledComment();

				// 比较关系
				JComboBox<String> compareRelation = new CompareComboBox<>();

				compareRelation.setModel(
						new DefaultComboBoxModel<>(new String[]{"=", "like", ">=", "<=", "!=", ">= && <="}));

				// 固定值
				JTextField unchangeValue = new JTextField();

				conditionsPanel.add(relationComBox);
				conditionsPanel.add(tableName);
				conditionsPanel.add(tableFiled);
				conditionsPanel.add(tableFiled_cn);
				conditionsPanel.add(filedType);
				conditionsPanel.add(filedComment);
				conditionsPanel.add(compareRelation);
				conditionsPanel.add(unchangeValue);
			}
		});
	}

	public void setDeleteQueryListener(JButton deleteQuery, JPanel querysPanel) {
		deleteQuery.addActionListener(e -> {

			//懒得抽方法了，冗余就冗余吧。。。

			// 获取容器个数
			int componentCount = querysPanel.getComponentCount();

			if (componentCount == 0) {
				return;
			}
			// 一行有6个
			// 如果是12，全部移除
			if (componentCount == 12) {
				querysPanel.removeAll();
				// 否则，移除最后6个
			} else {
				querysPanel.remove(componentCount - 1);
				querysPanel.remove(componentCount - 2);
				querysPanel.remove(componentCount - 3);
				querysPanel.remove(componentCount - 4);
				querysPanel.remove(componentCount - 5);
				querysPanel.remove(componentCount - 6);
			}

			frame.validate();
			frame.repaint();
		});
	}

	public void setAddQueryListener(JButton addQuery, JPanel querysPanel, String[] querysArr, Map<String, String> tableMap) {
		addQuery.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if (!canAddQuery(querysPanel)) {
					return;
				}

				if (querysPanel.getComponentCount() == 0) {
					for (String queryStr : querysArr) {
						JLabel label = new JLabel(queryStr);
						querysPanel.add(label);
					}
					addQueryMethod(querysPanel);
				} else {
					addQueryMethod(querysPanel);
				}

				frame.validate();
				frame.repaint();
			}

			private boolean canAddQuery(JPanel querysPanel) {

				if (querysPanel.getComponentCount() >= 10) {

					Component[] components = querysPanel.getComponents();
					for (int i = 6; i < components.length; i++) {

						if ("Filed_eng".equals(components[i].getClass().getSimpleName())) {

							Filed_eng filed_eng = (Filed_eng) components[i];
							filed_eng.setText(filed_eng.getText());

							if ("".equals(filed_eng.getText())) {
								JOptionPane.showMessageDialog(frame, "请先把当前内容填写完毕再增加查询字段信息！", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						} else if ("Filed_cn".equals(components[i].getClass().getSimpleName())) {

							Filed_cn filed_cn = (Filed_cn) components[i];
							filed_cn.setText(filed_cn.getText());

							if ("".equals(filed_cn.getText())) {
								JOptionPane.showMessageDialog(frame, "请先把当前内容填写完毕再增加查询字段信息！", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						} else if ("ServiceTypeComboBox".equals(components[i].getClass().getSimpleName())) {

							@SuppressWarnings("unchecked")
							ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) components[i];

							if ("布尔".equals(serviceTypeComboBox.getSelectedItem())
									|| "状态码".equals(serviceTypeComboBox.getSelectedItem())) {

								FiledComment filedComment = (FiledComment) components[i + 1];
								filedComment.setText(filedComment.getText());

								if ("".equals(filedComment.getText())) {

									JOptionPane.showMessageDialog(frame, "布尔或状态码的类型描述不能为空！！详细请见配置说明！", "提示",
											JOptionPane.INFORMATION_MESSAGE);
									return false;
								}

							}
						}

					}

				}

				return true;
			}

			private void addQueryMethod(JPanel querysPanel) {

				Set<String> tables = tableMap.keySet();
				String[] tableArr = tables.toArray(new String[]{});

				// 表名
				JComboBox<String> tableName = new JComboBox<>(tableArr);

				// 字段
				JTextField tableFiled = new Filed_eng();

				// 中文名称
				JTextField tableFiled_cn = new Filed_cn();

				// 字段类型
				JComboBox<String> filedType = new ServiceTypeComboBox<>();

				String[] typeList = new String[]{"字符串", "数字", "布尔", "状态码", "日期", "文字域"};

				filedType.setModel(new DefaultComboBoxModel<String>(typeList));

				// 类型描述
				JTextField filedComment = new FiledComment();

				// 是否可排序
				JComboBox<String> comboBox = new OrderComboBox<String>();
				comboBox.setModel(new DefaultComboBoxModel<String>(new String[]{"否", "是"}));

				querysPanel.add(tableName);
				querysPanel.add(tableFiled);
				querysPanel.add(tableFiled_cn);
				querysPanel.add(filedType);
				querysPanel.add(filedComment);
				querysPanel.add(comboBox);
			}

		});
	}

	public void setDeleteTableListener(JButton deleteTable, JPanel tablesPanel) {
		deleteTable.addActionListener(e -> {
			// 获取容器个数
			int componentCount = tablesPanel.getComponentCount();
			if (componentCount == 0) {
				return;
			}
			// 一行有五个
			// 如果是10，全部移除
			if (componentCount == 10) {
				tablesPanel.removeAll();
				// 否则，移除最后五个
			} else {
				tablesPanel.remove(componentCount - 1);
				tablesPanel.remove(componentCount - 2);
				tablesPanel.remove(componentCount - 3);
				tablesPanel.remove(componentCount - 4);
				tablesPanel.remove(componentCount - 5);
			}
			frame.validate();
			frame.repaint();
		});
	}

	public void setAddTableListener(JButton addTable, JButton addQuery, JButton addCondition, JPanel tablesPanel, String[] tablesArr) {
		addTable.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				addQuery.setEnabled(false);
				addCondition.setEnabled(false);

				if (tablesPanel.getComponentCount() == 0) {
					for (String tableStr : tablesArr) {
						JLabel label = new JLabel(tableStr);
						tablesPanel.add(label);
					}
					addTableMethod(tablesPanel);
					((Table2) tablesPanel.getComponent(7)).setEnabled(false);
					((Table1Fileds) tablesPanel.getComponent(8)).setEnabled(false);
					((Table1Fileds) tablesPanel.getComponent(8)).setText("/");
					((Table2Fileds) tablesPanel.getComponent(9)).setEnabled(false);
					((Table2Fileds) tablesPanel.getComponent(9)).setText("/");
				} else {
					addTableMethod(tablesPanel);
				}

				frame.validate();
				frame.repaint();

			}

			private void addTableMethod(JPanel tablesPanel) {

				java.util.List<String> table2List = new ArrayList<>();

				if (tablesPanel.getComponentCount() >= 5) {

					Component[] components = tablesPanel.getComponents();

					for (int i = 5; i < components.length; i++) {

						if ("Table1".equals(components[i].getClass().getSimpleName())) {

							Table1 table1 = (Table1) components[i];
							table1.setText(table1.getText());

							if ("".equals(table1.getText())) {
								JOptionPane.showMessageDialog(frame, "请先把当前内容填写完毕再增加关联表信息！", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return;
							}

							table2List.add(table1.getText());
						} else if ("Table1Fileds".equals(components[i].getClass().getSimpleName())) {

							Table1Fileds table1Fileds = (Table1Fileds) components[i];
							table1Fileds.setText(table1Fileds.getText());

							if ("".equals(table1Fileds.getText())) {
								JOptionPane.showMessageDialog(frame, "请先把当前内容填写完毕再增加关联表信息！", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return;
							}
						} else if ("Table2Fileds".equals(components[i].getClass().getSimpleName())) {

							Table2Fileds table2Fileds = (Table2Fileds) components[i];
							table2Fileds.setText(table2Fileds.getText());

							if ("".equals(table2Fileds.getText())) {
								JOptionPane.showMessageDialog(frame, "请先把当前内容填写完毕再增加关联表信息！", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return;
							}
						}

					}
				}

				JComboBox<String> relationComBox = null;
				// 如果是第一次添加
				if (tablesPanel.getComponentCount() == 5) {
					// 关联关系
					relationComBox = new JComboBox<>(new String[]{"from"});
				} else {
					// 关联关系
					relationComBox = new JComboBox<>(new String[]{"left join", "join", "right join"});
				}

				// 关联表
				Table1 table1 = new Table1();
				// 关联字段
				Table2 table2 = new Table2();

				if (tablesPanel.getComponentCount() >= 10) {
					table2.setModel(new DefaultComboBoxModel<>(table2List.toArray(new String[]{})));
				}

				Table1Fileds table1Fileds = new Table1Fileds();
				Table2Fileds table2Fileds = new Table2Fileds();

				tablesPanel.add(relationComBox);
				tablesPanel.add(table1);
				tablesPanel.add(table2);
				tablesPanel.add(table1Fileds);
				tablesPanel.add(table2Fileds);
			}
		});
	}

	public void setConfigIntroduceListener(JButton button) {
		button.addActionListener(e -> JOptionPane.showMessageDialog(frame,
				"表1字段、表2字段：多个字段使用 & 隔开，字段个数保持一致" + CodeConstant.NEW_LINE + "实体名称：用于生成方法的参数和返回值"
						+ CodeConstant.NEW_LINE + "类型描述：" + CodeConstant.NEW_LINE
						+ "    布尔示例：是#否 其中是和否填写数据库中用来表示是和否的值" + CodeConstant.NEW_LINE
						+ "    状态码示例：状态名称&状态值#状态名称&状态值（填写状态名称和状态值便于前台生成样式）" + CodeConstant.NEW_LINE
						+ "    其他类型将根据类型生成对应的样式，无需描述" + CodeConstant.NEW_LINE + "注意：关联表信息配置完点击确定才会生效！！！",
				"提示", JOptionPane.INFORMATION_MESSAGE));
	}

	/**
	 * 删除当前模块监听
	 *
	 * @param tableConfigExit
	 * @param methodListCombox
	 * @param conditionPanel
	 * @param querysPanel
	 * @param tablesPanel
	 */
	public void setDelMethodBtnListener(JButton delMethodBtn, JComboBox<String> tableConfigExit, JComboBox<String> methodListCombox, JPanel conditionPanel, JPanel querysPanel, JPanel tablesPanel) {
		delMethodBtn.addActionListener(e -> {
			// 选取的当前方法名
			String currentMethod = (String) methodListCombox.getSelectedItem();
			if ("--请选择--".equals(currentMethod)) {
				JOptionPane.showMessageDialog(null,
						"请选择要删除的方法！",
						"提示", JOptionPane.WARNING_MESSAGE);
				return;
			}
			// 选取的模块名
			String currentModel = (String) tableConfigExit.getSelectedItem();
			// 移除当前方法
			ChildWindowConstant.tablesQueryMap.get(currentModel).remove(currentMethod);
			methodListCombox.removeItem(currentMethod);

			//判断模块中是否还有值，如果为空，移除该模块
			if (ChildWindowConstant.tablesQueryMap.get(currentModel).isEmpty()) {
				ChildWindowConstant.tablesQueryMap.remove(currentModel);
				ChildWindowConstant.tablesQueryEndAndCnMap.remove(currentModel);
				tableConfigExit.removeItem(currentModel);
			}
			//清空
			currentModelName.setText("");
			currentModelName_cn.setText("");
			methodNameField.setText("");
			methodName_cnField.setText("");
			entityNameField.setText("");
			entityName_cnField.setText("");
			methodListCombox.setSelectedItem("--请选择--");
			tableConfigExit.setSelectedItem("--请选择--");
			clearPanel(conditionPanel, querysPanel, tablesPanel);
		});
	}

	private boolean checkRelTable(JPanel tablesPanel, java.util.List<TableRelationModel> tableRelationModelLists,
								  Map<String, String> tableMap) {

		// 清空集合
		tableRelationModelLists.clear();
		tableMap.clear();

		Component[] tableComponents = tablesPanel.getComponents();

		// 读取关联表的配置信息
		for (int i = 4; i < tableComponents.length; i++) {

			if ("JComboBox".equals(tableComponents[i].getClass().getSimpleName())) {

				@SuppressWarnings("unchecked")
				JComboBox<String> comboBox = (JComboBox<String>) tableComponents[i];

				TableRelationModel tableRelationModel = new TableRelationModel();

				tableRelationModel.setComboBox(comboBox);

				tableRelationModel.setRelation((String) comboBox.getSelectedItem());

				tableRelationModelLists.add(tableRelationModel);

			} else if ("Table1".equals(tableComponents[i].getClass().getSimpleName())) {
				Table1 table1 = (Table1) tableComponents[i];

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable1(table1);

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable1_text(table1.getText());
				table1.setText(table1.getText());

				// 表别名
				tableRelationModelLists.get(tableRelationModelLists.size() - 1)
						.setAnotherTableName("t" + (tableRelationModelLists.size() - 1));

			} else if ("Table2".equals(tableComponents[i].getClass().getSimpleName())) {

				Table2 table2 = (Table2) tableComponents[i];

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable2(table2);

				tableRelationModelLists.get(tableRelationModelLists.size() - 1)
						.setTable2_text((String) table2.getSelectedItem());
				table2.setSelectedItem(table2.getSelectedItem());

			} else if ("Table1Fileds".equals(tableComponents[i].getClass().getSimpleName())) {

				Table1Fileds table1Fileds = (Table1Fileds) tableComponents[i];

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable1Fileds(table1Fileds);

				tableRelationModelLists.get(tableRelationModelLists.size() - 1)
						.setTable1Fileds_text(table1Fileds.getText());
				table1Fileds.setText(table1Fileds.getText());

			} else if ("Table2Fileds".equals(tableComponents[i].getClass().getSimpleName())) {

				Table2Fileds table2Fileds = (Table2Fileds) tableComponents[i];

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable2Fileds(table2Fileds);

				tableRelationModelLists.get(tableRelationModelLists.size() - 1)
						.setTable2Fileds_text(table2Fileds.getText());
				table2Fileds.setText(table2Fileds.getText());

			}
		}

		// 如果集合大小为0，说明没配
		if (tableRelationModelLists.size() == 0) {
			JOptionPane.showMessageDialog(frame, "请先配置关联表信息！！！", "提示", JOptionPane.INFORMATION_MESSAGE);
			return false;

		}

		// 检查关联表配置有没有字段为空
		for (TableRelationModel tableRelationModel : tableRelationModelLists) {

			if ("".equals(tableRelationModel.getTable1_text()) || "".equals(tableRelationModel.getTable1Fileds_text())
					|| "".equals(tableRelationModel.getTable2Fileds_text())) {
				JOptionPane.showMessageDialog(frame, "表1，表1字段，表2字段不能为空！！请填写！！", "错误", JOptionPane.ERROR_MESSAGE);
				return false;

			}

			// 动态表名称使用
			tableMap.put(tableRelationModel.getTable1_text(), tableRelationModel.getAnotherTableName());

		}
		return true;

	}

	/**
	 * 清空所有
	 *
	 * @param conditionPanel
	 * @param querysPanel
	 * @param tablesPanel
	 */
	private void clearPanel(JPanel conditionPanel, JPanel querysPanel, JPanel tablesPanel) {
		tablesPanel.removeAll();
		querysPanel.removeAll();
		conditionPanel.removeAll();

		frame.validate();
		frame.repaint();
	}
}
